<template>
    <div class="container_box">
        <el-scrollbar class="main_box">
            <el-form
                ref="formRef"
                class="qwfriend-form"
                :model="formInfo"
                :rules="rules"
                label-width="auto"
                :disabled="pageType.isLook">
                <el-form-item label="任务名称" prop="title">
                    <el-input
                        v-model.trim="formInfo.title"
                        clearable
                        maxlength="20"
                        :show-word-limit="true"
                        placeholder="请输入任务名称">
                    </el-input>
                </el-form-item>
                <el-form-item label="发表成员" prop="work_user_search" class="qwfriend-form-radio-item">
                    <el-radio-group
                        v-model="formInfo.work_user_search"
                        @change="clearFormValidator('work_user_search')">
                        <el-radio :label="1">全部员工</el-radio>
                        <el-radio :label="2">指定员工</el-radio>
                    </el-radio-group>
                    <div v-if="formInfo.work_user_search === 2" class="radio-item-content">
                        <zw-unity-kit-select-items
                            v-model="formInfo.work_user_ids"
                            theme="info"
                            :disabled="pageType.isLook"
                            type="staff"
                            tag-btn-name="员工"
                            @change="validatorFormItem('work_user_search')" />
                    </div>
                </el-form-item>
                <el-form-item label="目标客户" prop="customer_search" class="qwfriend-form-radio-item">
                    <el-radio-group v-model="formInfo.customer_search" @change="clearFormValidator('customer_search')">
                        <el-radio :label="1">全部企微客户</el-radio>
                        <el-radio :label="2">指定企微客户</el-radio>
                    </el-radio-group>
                    <div v-if="formInfo.customer_search === 2" class="radio-item-content">
                        <zw-unity-kit-select-items
                            v-model="formInfo.customer_tag_ids"
                            theme="info"
                            :disabled="pageType.isLook"
                            type="custTag"
                            tag-btn-name="标签"
                            @change="validatorFormItem('customer_search')" />
                    </div>
                </el-form-item>
                <el-form-item label="朋友圈内容" prop="ref_type" class="qwfriend-form-radio-item">
                    <el-radio-group v-model="formInfo.ref_type" @change="handleChangeRefType">
                        <el-radio :label="2">手动输入</el-radio>
                        <el-radio :label="1">从朋友圈素材库选择</el-radio>
                    </el-radio-group>
                    <div v-show="formInfo.ref_type === 1" class="media-moment-wrap">
                        <el-button @click="openSelectMediaMoment">
                            <el-icon><Plus /></el-icon>
                            <span>选择朋友圈素材</span>
                            <zw-unity-kit-select-friend-material
                                v-model="selectFriendMaterialVisiabled"
                                @submit="onSelectFriendMaterialSubmit"></zw-unity-kit-select-friend-material>
                        </el-button>
                        <div v-if="formInfo.media_moment_id" class="media-moment">
                            <el-scrollbar class="media-moment-content" max-height="110px">
                                <div v-html="mediaMomentContent"></div>
                            </el-scrollbar>
                            <div
                                v-if="formInfo.media_moment_content?.attachment?.length"
                                class="media-moment-attachment">
                                <div
                                    v-if="formInfo.local_content_type === attachmentTypeEnum.image"
                                    class="moment-attachment-images">
                                    <el-image
                                        v-for="(item, index) in formInfo.media_moment_content.attachment"
                                        :key="index"
                                        :src="item.image?.url || item.local_image?.url">
                                        <template #error>
                                            <el-image
                                                src="//img.static-keyid.cn/toolspace/scrm/2023/09/1695815316881ocdqumpef0dfuk8m.png" />
                                        </template>
                                    </el-image>
                                </div>
                                <div
                                    v-if="formInfo.local_content_type === attachmentTypeEnum.video"
                                    class="moment-attachment-video"
                                    @click="openAttachmentVideo">
                                    <el-image
                                        class="video-play"
                                        src="//img.static-keyid.cn/toolspace/scrm/2023/09/16950360444828064pgh905i0j7md.png"></el-image>
                                    <el-image lazy :src="getVideoImage(getMediaMomentVideoUrl() as string, 46, 46)">
                                        <template #error>
                                            <el-image
                                                src="//img.static-keyid.cn/toolspace/scrm/2023/09/1695721780763mo89uo1sdqpp3r6z.png" />
                                        </template>
                                    </el-image>
                                </div>
                                <div
                                    v-if="formInfo.local_content_type === attachmentTypeEnum.link"
                                    class="moment-attachment-link">
                                    <el-image :src="getMediaMomentLink?.link_image_url">
                                        <template #error>
                                            <el-image
                                                src="//img.static-keyid.cn/toolspace/scrm/2023/09/1695721409722njc3nmed75g0kbaa.png" />
                                        </template>
                                    </el-image>
                                    <div class="link-info">
                                        <div
                                            :class="
                                                getMediaMomentLink?.link_decs ? `zw-text-ellipsis` : `zw-text-ellipsis2`
                                            ">
                                            {{ getMediaMomentLink?.link_title }}
                                        </div>
                                        <div
                                            v-if="getMediaMomentLink?.link_decs"
                                            class="zw-text-ellipsis link-info-desc">
                                            {{ getMediaMomentLink?.link_decs }}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-show="formInfo.ref_type === 2" class="material-content">
                        <ZwUnityMaterialContent
                            placeholder="请输入文本内容"
                            scene-value="friend"
                            :disabled="pageType.isLook"
                            :input-content-data="defaultInputContentData"
                            :material-content-data="defaultMaterialContentData"
                            @change-input-text="handleChangeInputText"
                            @change-material-list="handleChangeMaterialList" />
                        <div v-if="!pageType.isLook" class="qwfriend-desc">
                            附件非必选，因企业微信限制，最多支持9张图片，或者1个视频，或者1个链接
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="下发时间" prop="sync_wx_time" class="qwfriend-form-radio-item">
                    <el-radio-group v-model="formInfo.sync_wx_type" @change="clearFormValidator('sync_wx_time')">
                        <el-radio :label="1">立即下发</el-radio>
                        <el-radio :label="2">定时下发</el-radio>
                    </el-radio-group>
                    <div v-if="formInfo.sync_wx_type === 2" class="radio-item-content">
                        <el-date-picker
                            v-model="formInfo.sync_wx_time"
                            type="datetime"
                            placeholder="请选择下发时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            @change="handleChangeSyncTime" />
                    </div>
                    <div v-if="formInfo.sync_wx_type === 1 && pageType.isLook" class="detail-time">
                        {{ detailSyncTime || '--' }}
                    </div>
                </el-form-item>
                <el-form-item label="结束时间" prop="close_time">
                    <template v-if="pageType.isLook">
                        {{ formInfo.close_time || '--' }}
                    </template>
                    <template v-else>
                        <el-date-picker
                            v-model="formInfo.close_time"
                            type="datetime"
                            placeholder="请选择结束时间"
                            :default-time="new Date(0, 0, 0, 23, 59, 59)"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss" />
                        <div class="qwfriend-desc">设置结束时间后，到达结束时间未发表的成员将无法发表当前朋友圈。</div>
                    </template>
                </el-form-item>
            </el-form>
        </el-scrollbar>
        <div class="footer_box">
            <el-button @click="onCancel">
                {{ pageType.isLook ? '返回' : '取消' }}
            </el-button>
            <el-button v-if="!pageType.isLook" type="primary" @click="onSubmit">保存</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount, nextTick, computed } from 'vue';
import { useRoute } from 'vue-router';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash';

import { massCreate, getDetail, editFriend } from '@/api/friendcircle';
import router from '@/router';
import { getVideoImage, defaultTime } from '@/utils/utils';

import { IDetailFriendParams, IAttachmentItem, attachmentTypeEnum } from '../interface';
import { ElMessage } from '@zhongwan/element-plus';
const route = useRoute();
// const releaseType = ref();

const { type } = route.query || {};
/** 是否是查看禁用 */
const pageType = {
    isLook: type === 'look',
    isEdit: type === 'edit',
    isCopy: type === 'copy'
};
const formRef = ref<any>();
const formInfo = reactive<IDetailFriendParams>({
    /** 任务名称 */
    title: '',
    /** 发表成员员工ids */
    work_user_ids: [],
    /** 发表成员类型 1 全部员工 2指定员工  */
    work_user_search: 1,
    /** 目标客户类型 1 全部企微客户 2 指定标签 */
    customer_search: 1,
    /** 目标客户标签ids */
    customer_tag_ids: [],
    /** 朋友圈内容类型 1-朋友圈素材库 2-手动输入 */
    ref_type: 2,
    /** 朋友圈素材库id，如果没有的话就是0 */
    media_moment_id: 0,
    /** 素材类型 1图片 2视频 3链接 */
    local_content_type: 1,
    /** 素材内容 */
    moment_content: {
        content: '',
        attachment: []
    },
    /** 前端会用来展示朋友圈素材的附件内容, 调接口前把字段名会替换成moment_content */
    media_moment_content: {
        content: '',
        attachment: []
    },
    /** 群下发时间类型 1-立刻发送 2-指定时间发送 */
    sync_wx_type: 1,
    /** 下发时间 */
    sync_wx_time: '',
    /** 结束时间 */
    close_time: ''
});

/**
 * 初始化的朋友圈素材内容
 */
const defaultInputContentData = ref<string>('');
/**
 * 初始化朋友圈素材附件
 */
const defaultMaterialContentData = reactive<Array<IAttachmentItem>>([]);

/**
 * 素材库选择的文本展示
 */
const mediaMomentContent = computed(() => {
    // 处理用户输入的时候有换行的问题
    const content = String(formInfo.media_moment_content.content || '')
        .replace(/</g, `&lt;`)
        .replace(/>/g, `&gt;`)
        .replace(/\n/g, `<br />`);
    return content;
});
/**
 * 素材框文本发生变更
 * @param value 变更后的文字
 */
const handleChangeInputText = (value: string) => {
    formInfo.moment_content.content = value;
};

/**
 * 素材内容变更
 * @param attachment 素材内容
 */
const handleChangeMaterialList = (attachment: Array<IAttachmentItem>) => {
    formInfo.moment_content.attachment = [...attachment];
};

/* ----------------------------校验内容-start---------------------------- */
/**
 * 校验发表成员
 */
const validatorWorkUser = (value: any, rule: any, callback: any) => {
    // 全部员工不需要校验
    if (formInfo.work_user_search === 1) {
        return callback();
    }

    if (!formInfo.work_user_ids.length) {
        return callback(new Error('请选择指定员工'));
    }
    callback();
};

/**
 * 校验目标客户
 */
const validatorCustomer = (value: any, rule: any, callback: any) => {
    // 全部客户不需要校验
    if (formInfo.customer_search === 1) {
        return callback();
    }

    if (!formInfo.customer_tag_ids.length) {
        return callback(new Error('请选择指定企微客户'));
    }
    callback();
};

/**
 * 校验朋友圈内容
 */
const validatorMomentContent = (value: any, rule: any, callback: any) => {
    if (formInfo.ref_type === 1) {
        if (!formInfo.media_moment_id) {
            return callback(new Error('请选择朋友圈素材'));
        }
    } else {
        if (!formInfo.moment_content.content) {
            return callback(new Error('请输入朋友圈内容'));
        }
    }

    callback();
};

/**
 * 校验下发时间
 */
const validatorSyncTime = (value: any, rule: any, callback: any) => {
    // 立即发送不需要校验
    if (formInfo.sync_wx_type === 1) {
        return callback();
    }

    if (!formInfo.sync_wx_time) {
        return callback(new Error('请输入下发时间'));
    }

    if (dayjs(formInfo.sync_wx_time).isBefore(new Date())) {
        return callback(new Error('下发时间不能早于当前时间'));
    }
    callback();
};

/**
 * 校验结束时间
 */
const validatorCloseTime = (value: any, rule: any, callback: any) => {
    // 未填写不需要校验
    if (!formInfo.close_time) {
        return callback();
    }

    // 不能早于当前时间
    if (dayjs(formInfo.close_time).isBefore(new Date())) {
        return callback(new Error('结束时间不能早于当前时间'));
    }

    // 如果不需要填写下发时间不需要校验
    if (formInfo.sync_wx_type === 1) {
        return callback();
    }

    if (!dayjs(formInfo.close_time).isAfter(dayjs(formInfo.sync_wx_time))) {
        return callback(new Error('结束时间必须晚于下发时间'));
    }
    callback();
};

/**
 * 校验任务名称
 */
const validatorTitle = (value: any, rule: any, callback: any) => {
    // 未填写不需要校验
    if (!formInfo.title) {
        return callback(new Error('请输入任务名称'));
    }

    if (formInfo.title.length > 20) {
        return callback(new Error('任务名称不得超过20个字'));
    }
    return callback();
};
const rules = reactive({
    title: { required: true, validator: validatorTitle },
    work_user_search: { required: true, validator: validatorWorkUser },
    customer_search: { required: true, validator: validatorCustomer },
    ref_type: { required: true, validator: validatorMomentContent },
    sync_wx_time: { required: true, validator: validatorSyncTime },
    close_time: { validator: validatorCloseTime }
});

/**
 * 清理表单的校验
 * @param key 表单的props
 */
const clearFormValidator = async (key: string) => {
    await nextTick();
    formRef.value.clearValidate([key]);
};

/**
 * 字段变化时触发某一项校验
 */
const validatorFormItem = (key: string) => {
    formRef.value.validateField([key]);
};

/**
 * 下发时间变更时，校验结束时间
 */
const handleChangeSyncTime = () => {
    formRef.value.validateField(['close_time']);
    clearFormValidator('close_time');
};
/* ----------------------------校验内容-end---------------------------- */

/* ----------------------------朋友圈内容-start---------------------------- */
/**
 * 切换朋友圈素材内容时，更改一下当前素材的type类型
 */
const handleChangeRefType = () => {
    const mediaKey = formInfo.ref_type === 1 ? 'media_moment_content' : 'media_content';
    const type = formInfo[mediaKey]?.attachment?.[0]?.type as string;
    formInfo.local_content_type = attachmentTypeEnum[type || 'image'];
    clearFormValidator('ref_type');
};

/**
 * 获取视频素材的url
 */
const getMediaMomentVideoUrl = () => {
    const [videoMedia] = formInfo.media_moment_content?.attachment || [];
    const { video, local_video } = videoMedia;
    return video?.url || local_video?.url;
};

const openAttachmentVideo = () => {
    const videoUrl = getMediaMomentVideoUrl();
    if (!videoUrl) {
        ElMessage.warning('检查不到视频的url');
        return;
    }
    window.open(getMediaMomentVideoUrl());
};

/**
 * 获取链接素材的url
 */
const getMediaMomentLink = computed(() => {
    const [linkMedia] = formInfo.media_moment_content?.attachment || [];
    const { link, local_link } = linkMedia;
    return link || local_link;
});

/**
 * 是否显示选择朋友圈素材弹窗
 */
const selectFriendMaterialVisiabled = ref(false);

/**
 * 选择朋友圈素材弹窗确定回调用
 */
const onSelectFriendMaterialSubmit = (data: any) => {
    selectFriendMaterialVisiabled.value = false;

    formInfo.media_moment_id = data.id;
    formInfo.media_moment_content.content = data.content_text;

    if (data.type === attachmentTypeEnum.image) {
        // 图片
        formInfo.local_content_type = attachmentTypeEnum.image;
        formInfo.media_moment_content.attachment = data.mediaFileInfo?.map((item: any, index: number) => {
            const { absolute_url, content_id, code } = item;
            const imageType = content_id ? 'image' : 'local_image';
            return {
                type: imageType,
                [imageType]: {
                    content_id,
                    code,
                    url: absolute_url
                },
                sort: index
            };
        });
    } else if (data.type === attachmentTypeEnum.video) {
        // 视频
        formInfo.local_content_type = attachmentTypeEnum.video;
        const { absolute_url, content_id, code } = data.mediaFileInfo?.[0] || {};
        const videoType = content_id ? 'video' : 'local_video';
        formInfo.media_moment_content.attachment = [
            {
                type: videoType,
                [videoType]: {
                    content_id: content_id,
                    code,
                    url: absolute_url
                },
                sort: 1
            }
        ];
    } else if (data.type === attachmentTypeEnum.link || (data.mediaLinkInfo && !Array.isArray(data.mediaLinkInfo))) {
        // 链接
        formInfo.local_content_type = attachmentTypeEnum.link;
        const { link_decs, link_share_image, link_title, link_url, content_id, code } = data.mediaLinkInfo;
        const linkType = content_id ? 'link' : 'local_link';
        formInfo.media_moment_content.attachment = [
            {
                type: linkType,
                [linkType]: {
                    content_id,
                    link_decs,
                    link_image_url: link_share_image,
                    link_title,
                    link_url,
                    code
                },
                sort: 1
            }
        ];
    }
};

/**
 * 打开朋友圈素材选择
 */
const openSelectMediaMoment = () => {
    // 在这里打开选择朋友圈素材弹窗
    selectFriendMaterialVisiabled.value = true;
};

/* ----------------------------朋友圈内容-end---------------------------- */

/**
 * 查看页面时展示的立即下发的时间
 * 编辑时所需要的判断详情的下发时间
 */
const detailSyncTime = ref('');

/**
 * 取消创建/编辑
 */
const onCancel = () => {
    router.back();
};

/**
 * 保存朋友圈任务
 */
const onSubmit = async () => {
    await formRef.value.validate();
    const params: any = cloneDeep(formInfo);
    // 处理选择员工
    if (params.work_user_search === 1) {
        params.work_user_ids = [];
    } else {
        params.work_user_ids = params.work_user_ids.map(item => item.id);
    }
    // 处理选择客户
    if (params.customer_search === 1) {
        params.customer_tag_ids = [];
    } else {
        params.customer_tag_ids = params.customer_tag_ids.map(item => item.id);
    }

    // 处理选择朋友圈素材
    if (params.ref_type === 1) {
        // 朋友圈素材选择
        params.moment_content = params.media_moment_content;
    } else {
        // 手动输入
        params.media_moment_id = 0;
    }
    params.media_moment_content = undefined;

    if (params.sync_wx_type === 1) {
        params.sync_wx_time = '';
    }

    params.moment_content.attachment.forEach((item: IAttachmentItem) => {
        // 因为后端表里用的是decs，而公共组件以及其他地方都是desc。因此做个转换
        if (['local_link', 'link'].includes(item.type)) {
            const { link_desc, link_decs } = item[item.type];
            item[item.type].link_decs = link_decs || link_desc;
            item[item.type].link_desc = undefined;
        }
    });

    // 处理素材的类型
    const contentType = params.moment_content.attachment?.[0]?.type as string;
    params.local_content_type = attachmentTypeEnum[contentType || 'image'];

    const { type } = route.query || {};

    if (type === 'copy') {
        params.id = undefined;
    }

    let successMsg = '创建成功';
    let submitApi = massCreate;
    if (type === 'edit') {
        successMsg = '修改成功';
        submitApi = editFriend;

        // 非创建失败的编辑
        if (params.sync_wx_status !== 2 && dayjs(detailSyncTime.value).isBefore(new Date())) {
            ElMessage.error('当前朋友圈任务已下发，无法编辑');
            return;
        }
    }
    await submitApi(params);
    ElMessage.success(successMsg);
    router.back();
};

// 获取详情
const initDetailInfo = async () => {
    const { type, id } = route.query || {};
    if (!['edit', 'copy', 'look'].includes(type as string)) {
        return;
    }

    const res = await getDetail({ send_moment_id: id });
    detailSyncTime.value = res.sync_wx_time;

    if (res.media_moment_id) {
        res.media_moment_content = res.moment_content;
        res.moment_content = {
            attachment: [],
            content: ''
        };
    }

    // 处理图片/链接返回应该放在local_image里
    res.moment_content.attachment.forEach((item: IAttachmentItem) => {
        /**
         * 替换属性名
         * @param attrName 属性名
         * @param replaceBefore 替换之前的钩子函数。（目前只处理链接的描述字段）
         */
        const replaceAttachmentAttrName = (attrName: string, replaceBefore?: () => void) => {
            // 不等于不需要替换
            if (item.type !== attrName) {
                return;
            }

            replaceBefore?.();

            // 如果是素材类型为素材库选择的，不需要替换
            if (item[attrName]?.content_id) {
                return;
            }

            item[`local_${attrName}`] = item[attrName];
            item[attrName] = undefined;
            item.type = `local_${attrName}`;
            // 链接的类型的code字段都在对应类型的字段里，其他的放在了item里
            item[item.type].code = item[item.type].code || item.code;
        };

        replaceAttachmentAttrName('image');
        replaceAttachmentAttrName('video');
        replaceAttachmentAttrName('link', () => {
            const { link_decs, link_desc } = item.link as any;
            item.link.link_desc = link_decs || link_desc;
        });

        // 复制的情况下删除所有的id字段
        if (pageType.isCopy && item[item.type]) {
            item[item.type].id = undefined;
        }
    });

    if (pageType.isCopy) {
        res.title += '副本';
    }
    Object.assign(formInfo, res);

    // 手动处理一遍content_type的类型
    handleChangeRefType();
    defaultInputContentData.value = formInfo.moment_content.content;
    defaultMaterialContentData.length = 0;
    defaultMaterialContentData.push(...cloneDeep(formInfo.moment_content.attachment));

    // 不知道为什么用nextTick不行，所以使用setTimeout
    setTimeout(() => {
        formRef.value.clearValidate();
    });
};

onBeforeMount(initDetailInfo);
</script>

<style lang="scss" scoped>
@import './index';
</style>
